<?php

namespace Modules\Admin\Services;

use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Config;
use Modules\Admin\Models\Admin;
use Modules\Common\StatusData;
use Tymon\JWTAuth\Facades\JWTAuth;
use  \Illuminate\Http\JsonResponse;

class AuthService extends BaseService
{
    public function __construct()
    {
        Config::set('auth.defaults.guard','admin');
    }

    /***
     * @param array $data
     * @return JsonResponse
     * 登录
     */
    public function login(array $data): JsonResponse
    {

        if (!Auth::guard('admin')->attempt($data)){
            return $this->buildFailed(StatusData::LOGIN_ERROR,'用户名或密码错误!');
        }
        $userInfo = Admin::where(['username' => $data['username']])->first();
        $userInfo = $userInfo->toArray();
        $user = [
            'id' => $userInfo['id'],
            'username' => $userInfo['username'],
            'password' => $data['password']
        ];
        $token = $this->setToken($user);
        if (!count($token)){
            return $this->buildFailed(StatusData::AUTH_ERROR,'Token获取失败!  ');
        }
        $userInfo = array_merge($userInfo,$token);
        return $this->buildSuccess($userInfo);
    }

    /***
     * @return void
     * 退出登录
     */
    public function logout(): JsonResponse
    {
      JWTAuth::parseToken()->invalidate();
      return $this->buildSuccess([],'已退出登录');
    }

    /***
     * @return mixed
     * 我的信息
     */
    public function me()
    {
        return JWTAuth::parseToken()->touser();
    }

    /***
     * @param array $data
     * @return array
     * 获取token
     */
    public function setToken(array $data): array
    {
        if (!$token = JWTAuth::attempt($data)){
            return [];
        }
        return $this->respondWithToken($token);
    }

    /**
     * @param string $token
     * @return array
     *
     */
    protected function respondWithToken(string $token): array
    {
        return [
            'token' => $token,
            'token_type' => 'bearer',
            'expires_in' => JWTAuth::factory()->getTTL() * 60
        ];
    }
}
